#include "catalog.hpp"

namespace DaseX {

RC CataLog::register_table(TableInfo &table_info) {
    RC rc = RC::FAILED;
    auto it = table_infos.find(table_info.table_name);
    if (it != table_infos.end()) {
        rc = RC::TABLE_ALREADY_EXISTS;
        return rc;
    }
    std::lock_guard<std::mutex> lock(mutex_catalog);
    table_infos.emplace(table_info.table_name, table_info);
    std::shared_ptr<Table> table = std::make_shared<Table>(table_info);
    tables.emplace(table_info.table_name, table);
    rc = RC::SUCCESS;
    return rc;
}

RC CataLog::delete_table(std::string table_name) {
    RC rc = RC::FAILED;
    std::lock_guard<std::mutex> lock(mutex_catalog);
    auto it = table_infos.find(table_name);
    if (it == table_infos.end()) {
        rc = RC::TABLE_NOT_EXISTS;
        return rc;
    }
    table_infos.erase(table_name);
    tables.erase(table_name);
    rc = RC::SUCCESS;
    return rc;
}

RC CataLog::get_table(std::string table_name, std::shared_ptr<Table> &table) {
    RC rc = RC::FAILED;
    auto it = table_infos.find(table_name);
    if (it == table_infos.end()) {
        rc = RC::TABLE_NOT_EXISTS;
        return rc;
    }
    table = tables[table_name];
    rc = RC::SUCCESS;
    return rc;
}

CataLog global_catalog;

} // namespace DaseX
